import React, { Component, PureComponent } from 'react'

import { toNumber, cloneDeep } from 'lodash'

import $axios from '@/plugins/axios'
import { $basics } from '@/plugins/eng_config'

import moment from 'moment';

import { Form, Input, Button, Select, Row, Col, Divider, TreeSelect, Cascader, DatePicker } from 'antd';

const { Search } = Input

const { Option } = Select

const { TreeNode } = TreeSelect;

const layout = {
  labelCol: {
    span: 8,
  },
  wrapperCol: {
    span: 16,
  },
};



const options = [
  {
    value: 'zhejiang',
    label: 'Zhejiang',
    children: [
      {
        value: 'hangzhou',
        label: 'Hangzhou',
        children: [
          {
            value: 'xihu',
            label: 'West Lake',
          },
        ],
      },
    ],
  },
  {
    value: 'jiangsu',
    label: 'Jiangsu',
    children: [
      {
        value: 'nanjing',
        label: 'Nanjing',
        children: [
          {
            value: 'zhonghuamen',
            label: 'Zhong Hua Men',
          },
        ],
      },
    ],
  },
];

// let testList = [1, 2]

export default class FormSearch extends PureComponent {

	  formRef = React.createRef();

    constructor(props){
				super(props)
				this.state.list = cloneDeep(props.list)

				const { list } = this.state

				list.forEach((item, index) => {

					const sign = (item.dictCode && item.src) || (item.dictCode && item.fn) || (item.src && item.fn)
					if (sign) {
						console.error('表单配置文件中 属性 fn, dictCode, src 不要同时存在，注意代码书写。')
					}

					if (typeof item.dictCode === 'string') {  // 字符串 -- 远程 获取 字典值的 参数
						this.getDicts(list, index, list[index].time)
					}

					if(item.src){	// 说明需要远程获取数据源
						this.getOriginOptions(list, index, list[index].time)
					}

					if (item.fn && typeof item.fn === 'function') {  // 必须返回一个 Promise
						item.fn().then(res => {
							list[index].options = res || []
							this.setState({
								list: cloneDeep(list)
							})
						})
					}

				})
    }

		state = {
			testList:[1,2],
		}

	loadData = (selectedOptions) => {
			const targetOption = selectedOptions[selectedOptions.length - 1];
			targetOption.loading = true;
		}

	getLoadData = (list, index) => {
		return list[index].loadData.bind('', this, list, index)
	}

		getDicts = (list, index, time = 2000) => {
			const param = {
				dicTypes: list[index].dictCode,
				dictBusiType: 'BUSI_DICT'
			}
			$axios.post(`${$basics}/basics/dict/list`, param).then(res => {
				list[index].options = res.body[list[index].dictCode] || []
				this.setState({
					list: cloneDeep(list)
				})
			})
			// setTimeout(() => {
			// 	list[index].options = [
			// 		{ label: 'A', value: 'aaaa' },
			// 		{ label: 'B', value: 'bbbb' },
			// 		{ label: 'C', value: 'ccc' }
			// 	]
			// 	this.setState({
			// 		list: cloneDeep(list)
			// 	})
			// }, time)
		}

		getOriginOptions = (list, index, time=2000) => {
			setTimeout(() => {
				list[index].options = [1,2,3,4,5,6,7,8]
				this.setState({
					list: cloneDeep(list)
				})
			}, time)
		}

		onFinish = (values) => {
			const val = this.formRef.current.getFieldsValue()
			// console.log(this.formRef.current.getFieldsValue());
			// const val = this.formRef.current.getFieldsValue().startTime
			// console.log(typeof	 val)
			// console.log(val, val.format('YYYY-MM-DD'))
			const { onFinish } = this.props
			typeof onFinish === 'function' && onFinish(val)
		};

		onReset = () => {
			this.formRef.current.resetFields()
		}

		getController = (item, index) => {
			const { type } = item

			if( type === 'slot' ){		// 如果是 插槽
				const { children } = this.props
				if( Array.isArray(children) ){	// 如果是 多个 插槽
					const child = children.find(r => {
						const { name } = r.props
						return name === item.prop
					})
					if( child ) return child
				}else{
					return children
				}
			}

			if( type === 'Input' ){
				return <Input placeholder={item.placeholder || item.label} />
			}

			if( type === 'Search' ){
				return <Search disabled onSearch={(value) => this.formItemOperate({item, value})} placeholder={item.placeholder || item.label} />
			}

			if( type === 'Select' ){
				return (
					<Select showSearch mode={item.multiple ? 'multiple' : null} allowClear size='middle'>
						{
							(item.options || []).map((r, i) => (
								<Option key={i} value={r.dicValue || r.value}>{r.dicLabel || r.label}</Option>
							))
						}
					</Select>
				)
			}
			if( type === 'TreeSelect' ){
				return (
					<TreeSelect
					showSearch
					placeholder="Please select"
					allowClear
					treeDefaultExpandAll
					treeData={item.options}
					>
						{/* <TreeNode value="parent 1" title="parent 1" disabled>
							<TreeNode value="parent 1-0" title="parent 1-0" disabled>
								<TreeNode value="leaf1" title="my leaf" />
								<TreeNode value="leaf2" title="your leaf" />
							</TreeNode>
							<TreeNode value="parent 1-1" title="parent 1-1" disabled>
								<TreeNode value="sss" title={<b style={{ color: '#08c' }}>sss</b>} />
							</TreeNode>
						</TreeNode> */}
					</TreeSelect>
				)
			}
			if( type === 'Cascader' ){
				return <Cascader fieldNames={{ label: 'title' }} loadData={this.getLoadData(this.state.list, index)} options={item.options} placeholder={item.placeholder || item.label} changeOnSelect />
			}
			if( type === 'DatePicker' ){
				return <DatePicker style={{ display: 'block' }} picker={item.picker || null} placeholder={item.placeholder || item.label}/>
			}
		}

		formItemOperate = ({item, value}) => {
			const { formItemCallback } = this.props
			if(typeof formItemCallback === 'function'){
				formItemCallback({item ,value})
			}
		}

		onSearch = (a, b) =>{

		}

		onChange = (item) => {
			return (value, dateString) => {
				this.formRef.current.setFieldsValue({
					[item.prop]: dateString
				})
			}
		}

		setFieldsValue = (item) => {
			this.formRef.current.setFieldsValue(item)			// item  键值对  key: value			
		}

		fffff = (a, b) => {
			return a.format('YYYY--MM--DD')
		}

    render() {
			const { list = [] } = this.state
        return (
						<>
							<Form
								{...layout}
								ref={this.formRef}
								name="basic"
								size="middle"
								labelAlign="left"
								onFieldsChange={this.props.onFieldsChange || function(){}}
								onFinish={this.onFinish}
								// initialValues={{field1: 1, startTime:moment('2015-01-01', 'YYYY-MM-DD')}}
							>
								{
									list.map((item, index) => (
										<Form.Item key={index} label={item.label} name={item.prop}>
											{
												this.getController(item, index)
											}
										</Form.Item>											
									))
								}
							</Form>   
							<Row gutter={16}>
								<Col className="gutter-row" span={12}>
									<Button type="primary" htmlType="button" onClick={this.onFinish} block>查询</Button>
								</Col>
								<Col className="gutter-row" span={12}>
									<Button htmlType="button" onClick={this.onReset} block>重置</Button>
								</Col>
							</Row>							
					</>             
        )
    }
}
